/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.user.shared;

import java.util.ArrayList;
import java.util.Collection;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNull;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;

/**
 * The utility class provides methods for manipulating {@link SimpleObject}s.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public abstract class Serializer {

  /**
   * Converts json string to object.
   * 
   * @param jsonString the json string
   * @return the object
   */
  @SuppressWarnings("unchecked")
  public static <T> T fromJson(String jsonString) {
    if (jsonString == null || jsonString.isEmpty()) {
      return null;
    }
    return (T) fromJsonValue(JSONParser.parseLenient(jsonString));
  }

  /**
   * Converts json value to object.
   * 
   * @param jsonValue the json value
   * @return the object
   */
  public static Object fromJsonValue(JSONValue jsonValue) {
    if (jsonValue.isNull() != null) {
      return null;
    }

    if (jsonValue.isNumber() != null) {
      return jsonValue.isNumber().doubleValue();
    } else if (jsonValue.isBoolean() != null) {
      return jsonValue.isBoolean().booleanValue();
    } else if (jsonValue.isString() != null) {
      return jsonValue.isString().stringValue();
    } else if (jsonValue.isArray() != null) {
      JSONArray jsonArray = jsonValue.isArray();
      Collection<Object> collection = new ArrayList<Object>();
      for (int i = 0; i < jsonArray.size(); i++) {
        collection.add(fromJsonValue(jsonArray.get(i)));
      }
      return collection;
    } else {
      JSONObject jsonObject = jsonValue.isObject();
      SimpleObject simpleObject = new SimpleObject();
      for (String key : jsonObject.keySet()) {
        simpleObject.put(key, fromJsonValue(jsonObject.get(key)));
      }
      return simpleObject;
    }
  }

  /**
   * Converts object to json string.
   * 
   * @param jsonizable the expected value of json-compatible type (String, Number, Boolean,
   *          Collection, SimpleObject).
   * @return the json string
   */
  public static String toJson(Object jsonizable) {
    return toJsonValue(jsonizable).toString();
  }

  /**
   * Converts object to json value.
   * 
   * @param jsonizable the expected value of json-compatible type (String, Number, Boolean,
   *          Collection, SimpleObject).
   * @return the json value
   */
  @SuppressWarnings("unchecked")
  private static JSONValue toJsonValue(Object jsonizable) {
    if (jsonizable == null) {
      return JSONNull.getInstance();
    }

    if (jsonizable instanceof String) {
      return new JSONString((String) jsonizable);
    } else if (jsonizable instanceof Number) {
      return new JSONNumber(((Number) jsonizable).doubleValue());
    } else if (jsonizable instanceof Boolean) {
      return JSONBoolean.getInstance((Boolean) jsonizable);
    } else if (jsonizable instanceof SimpleObject) {
      JSONObject jsonMap = new JSONObject();
      SimpleObject simpleObject = (SimpleObject) jsonizable;
      for (String key : simpleObject.keySet()) {
        JSONValue value = toJsonValue(simpleObject.get(key));
        if (value.isNull() == null) {
          jsonMap.put(key, value);
        }
      }
      return jsonMap;
    } else if (jsonizable instanceof Collection) {
      JSONArray jsonArray = new JSONArray();
      int i = 0;
      for (Object value : (Collection<Object>) jsonizable) {
        jsonArray.set(i++, toJsonValue(value));
      }
      return jsonArray;
    }
    throw new IllegalArgumentException("Unable to serialize from type ["
        + jsonizable.getClass().getName() + "]");
  }

}
